"use client"

import type React from "react"
import { useEffect } from "react"
import { Modal, Form, Input, Select, Space, Button, Typography } from "antd"
import type { Host, HostType } from "../types"
import { HOST_TYPE_NAMES } from "../types"

const { TextArea } = Input
const { Text } = Typography

interface AddEditHostDialogProps {
  open: boolean
  editingHost: Host | null
  categories: string[]
  onClose: () => void
  onSubmit: (values: Partial<Host>) => Promise<void>
}

export const AddEditHostDialog: React.FC<AddEditHostDialogProps> = ({
  open,
  editingHost,
  categories,
  onClose,
  onSubmit,
}) => {
  const [form] = Form.useForm()

  useEffect(() => {
    if (open && editingHost) {
      form.setFieldsValue(editingHost)
    } else {
      form.resetFields()
    }
  }, [open, editingHost, form])

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      await onSubmit(values)
      form.resetFields()
    } catch (error) {
      console.error("Validation failed:", error)
    }
  }

  const validateIP = (_: any, value: string) => {
    const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/
    const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/

    if (!value) {
      return Promise.reject("请输入IP地址")
    }

    if (!ipv4Regex.test(value) && !ipv6Regex.test(value)) {
      return Promise.reject("请输入有效的IPv4或IPv6地址")
    }

    if (ipv4Regex.test(value)) {
      const parts = value.split(".")
      for (const part of parts) {
        const num = Number.parseInt(part, 10)
        if (num < 0 || num > 255) {
          return Promise.reject("IPv4地址的每个部分必须在0-255之间")
        }
      }
    }

    return Promise.resolve()
  }

  return (
    <Modal
      title={editingHost ? "编辑主机" : "添加主机"}
      open={open}
      onCancel={() => {
        form.resetFields()
        onClose()
      }}
      footer={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
      maskClosable={false}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: "other" as HostType,
          category: categories[0],
        }}
      >
        <Form.Item name="title" label="名称" rules={[{ required: true, message: "请输入主机名称" }]}>
          <Input placeholder="请输入主机名称" maxLength={50} showCount />
        </Form.Item>

        <Space style={{ width: "100%" }} size="middle">
          <Form.Item
            name="ip"
            label="IP地址"
            rules={[{ required: true, validator: validateIP }]}
            style={{ width: "100%" }}
          >
            <Input placeholder="请输入IP地址" />
          </Form.Item>

          <Form.Item
            name="domain"
            label="域名"
            rules={[{ required: true, message: "请输入域名" }]}
            style={{ width: "100%" }}
          >
            <Input placeholder="请输入域名" />
          </Form.Item>
        </Space>

        <Space style={{ width: "100%" }} size="middle">
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: "请选择主机类型" }]}
            style={{ width: "100%" }}
          >
            <Select>
              {Object.entries(HOST_TYPE_NAMES).map(([value, label]) => (
                <Select.Option key={value} value={value}>
                  {label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="category"
            label="分组"
            rules={[{ required: true, message: "请选择分组" }]}
            style={{ width: "100%" }}
          >
            <Select>
              {categories.map((category) => (
                <Select.Option key={category} value={category}>
                  {category}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Space>

        <Form.Item name="description" label="描述">
          <TextArea placeholder="请输入主机描述信息" autoSize={{ minRows: 2, maxRows: 6 }} maxLength={200} showCount />
        </Form.Item>

        <Form.Item
          name="hostContent"
          label="hosts内容"
          help={<Text type="secondary">格式示例：127.0.0.1 localhost</Text>}
        >
          <TextArea placeholder="请输入hosts配置内容" autoSize={{ minRows: 2, maxRows: 6 }} />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default AddEditHostDialog
